<?php

namespace Modules\Buy\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Buy\Entities\Adress;
use Modules\Buy\Entities\Card;
use Modules\Buy\Entities\Collection;
use Modules\Buy\Entities\Good;
use Modules\Buy\Entities\Huowu;
use Modules\Buy\Entities\Order;
use Modules\Buy\Entities\Orderlist;

class CardController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
//    购物车页面
    public function index()
    {
//        从购物车里获得数据往首页循环
        $card = Card::where('user_id',\Auth::guard('shop')->user()->id)->get();
//        dd(123);
//        dd($card->toArray());
//        if ()
        return view('shop.shopcart',compact('card'));
    }

//    添加到购物车的ajax方法
    public function addcard(Request $request)
    {
//        return 123;die;
        $post = $request->all();
//        return $post;die;
        $userid = \Auth::guard('shop')->user()->id;
        //通过商品id找到商品单价
        $goodsPrice = Good::find($post['good_id'])->mallprice;
        //通过货品id找到该用户想买的货品的附加价格
        $huopinPrice = Huowu::find($post['huowu_id'])->fujiaprice;
        //计算小计,使用商城价加上附加价格,然后乘以购买数量
        $xiaoji = ($goodsPrice + $huopinPrice) * $post['num'];
        Card::create([
            'good_id' => $post['good_id'],
            'huowu_id' => $post['huowu_id'],
            'num' => $post['num'],
            'xiaoji' => $xiaoji,
            'user_id' => $userid,
        ]);
        return ['valid' => 1,'message' => '加入购物车成功'];
    }

//    删除商品
    public function del($id)
    {
//        return 123;
//        return $id;
        Card::destroy($id);

        return ['status'=>1,'message'=>'删除成功'];
    }


//    加载订单列表
    public function order()
    {
//        获取购物车表的数据
        $card = Card::where('user_id',\Auth::guard('shop')->user()->id)->get();

//        获取地址管理的数据，往页面展示
        $adress = Adress::limit(3)->get();
//        dd($adress->toArray());

        $moren = Adress::where('status',1)->first();
//        dd($moren->toArray());
        return view('shop.order',compact('card','adress','moren'));
    }

//    提交订单发送异步
    public function suborder(Request $request)
    {
//        return 123;
        $post  = $request->all();
//        dd($post);
//        获取到地址id和订单总价就可以往表里边存了
//        return $post;
        $order = Order::create([
            'orderId' => md5(time()), //一定要保证订单编号唯一
            'total' => $post['total'],
            'user_id' => \Auth::guard('shop')->user()->id,
            'address_id' => $post['addressid'],
            'status' => 0,

        ]);

//        从购物车当中获取用户数据，然后循环存入订单列表中
        $card = Card::where('user_id',\Auth::guard('shop')->user()->id)->get();
        foreach ($card as $v){
            Orderlist::create([
                'orderId' => $order['orderId'],
                'huowu_id' => $v['huowu_id'],
                'good_id' => $v['good_id'],
                'xiaoji' => $v['xiaoji'],
                'num' => $v['num'],
            ]);
        }

//        找到对应的货品，库存减去你买的数量
        foreach ($card as $v){
            $huowu = Huowu::find($v['huowu_id']);
            $huowu['kucun'] = $huowu['kucun']-$v['num'];
            $huowu->save();
        }
//        然后清空购物车
        Card::where('user_id',\Auth::guard('shop')->user()->id)->delete();
        return ['volid'=>1,'message'=>'订单提交成功,请付款','data'=>$order['orderId']];
    }    

//    提交订单直接跳到付款页面
    public function pay($orderId)
    {
//        dd($orderId);

        $card = Card::where('user_id',\Auth::guard('shop')->user()->id)->get();

        $order = Order::where('orderId',$orderId)->first();

//        dd($order->toArray());
        require_once public_path("/weixinpay/lib/WxPay.Api.php");
        require_once public_path("/weixinpay/example/WxPay.NativePay.php");

        $input = new \WxPayUnifiedOrder();
        $input->SetBody("吃货天堂"); //设置支付页面顶部文字提示
        $input->SetAttach($orderId); //暂时不管,这个最重要
        $input->SetOut_trade_no("sdkphp123456789".date("YmdHis")); //设置商户平台的订单号
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetTotal_fee('1');  //设置订单总金额,必须是整数
        $input->SetNotify_url(
            "http://chi.heguozhen.cn/notify"
        ); //不是必填,如果不填,就去wxpay.config.php文件中找对应值,当前是laravel框架,由于框架的特殊性,只能通过路由请求,所以这里应该填写的是域名+某个处理回调通知方法的路由地址,并且一定要将该地址让laravel框架阻止csrd验证
        $input->SetTrade_type("NATIVE"); //设置支付方式,如果是扫码支付,一定是NATIVE不能改
        $input->SetProduct_id("123456789");
        $notify = new \NativePay();
        $result = $notify->GetPayUrl($input);
        $url = $result["code_url"];

        return view('shop.pay',compact('card','url','order'));
//        return 123;
    }

    public function notify()
    {
//        dd(123);
        //获取微信发来的请求
        $data = file_get_contents('php://input');
        $data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
//        file_put_contents('data.php', var_export($data, true));
        //通过微信发来的消息判断是否支付成功
        if ($data->result_code == 'SUCCESS' && $data->return_code == 'SUCCESS'){
            //进来之后,通过获取微信返回给我们的那个附加参数,也就是当前付款的订单编号,找到对应订单,将订单状态改成1
            $order = Order::where('orderId',$data->attach)->first();
            $order->status = 1;
            $order->save();
            //然后我们需要回复给微信端,告诉他们我们成功收到了你发来的消息
            return true;
        }
    }

//    检测是否支付路由
    public function checkStatus($orderId){
        //通过订单编号找到订单数据,根据状态值判断返回内容
        $order = Order::where('orderId',$orderId)->first();
        return $order['status'] ? ['valid' => 1, 'message' => '支付成功'] : ['valid' => 0, 'message' => '尚未支付'];
    }


//    支付成功后跳的路由
    public function success($orderId)
    {
//        dd($orderId);
        $adress = Adress::where('status',1)->first();
        $card = Card::where('user_id',\Auth::guard('shop')->user()->id)->get();
//        根据订单id找到订单列表，再找到货物id，和商品id，然后分配到页面
        $orderlist  = Orderlist::where('orderId',$orderId)->get();
//        dd($orderlist->toArray());
//        $good = Good::whereIn('id',$orderlist['good_id'])->pluck('id');


//        组好返回出去
//        $good = Orderlist::where('good_id',)->get();
//        dd($good->toArray());
        $order = Order::where('orderId',$orderId)->first();
//        dd($order->toArray());

        return view('shop.success',compact('adress','card','orderlist','order'));
    }


//    订单列表页面
    public function orderlist(Order $order)
    {
        $card = Card::where('user_id',\Auth::guard('shop')->user()->id)->get();

//        获得所有的订单，前台页面循环展示
        $dingdan = Order::where('user_id',\Auth::guard('shop')->user()->id)->get();
//        dd($dingdan->toArray());

//        首先获得到订单列表
//        foreach ($dingdan as $k=>$v){
//            $orderlist = Orderlist::where('orderId',$v['orderId'])->get()->toArray();
//            $dingdan[$k]['list'][] = $orderlist;
//        }
//        dd($dingdan);
//        dd($data);
//        获得状态为0的数据往页面分配
        $orderzero = Order::where('status',0)->get();
//        dd($orderzero->toArray());
//        找到状态为1的往页面循环
        $orderone= Order::where('status',1)->get();

//        找到状态为2的，分配到模板
        $ordertwo = Order::where('status',2)->get();

        return view('shop.orderlist',compact('card','dingdan','orderzero','orderone','ordertwo'));

    }

//    删除订单数据
    public function shanchu($orderId)
    {
//        return 123;
        Order::where('orderId',$orderId)->delete();

        Orderlist::where('orderId',$orderId)->delete();

//        dd($order->toArray());
        return ['volid'=>1,'message'=>'删除成功'];
    }

//    取消订单
    public function quxiao($orderId)
    {
//        return 123;
        Order::where('orderId',$orderId)->delete();

        Orderlist::where('orderId',$orderId)->delete();

//        dd($order->toArray());
        return ['volid'=>1,'message'=>'取消成功'];
    }


//    配置收藏路由
    public function shoucang($goodid)
    {
//        dd(123);
        Collection::create([
            'user_id'=>\Auth::guard('shop')->user()->id,
            'good_id'=>$goodid
        ]);
        return ['volid'=>1,'message'=>'收藏成功'];
    }


}
